<template>
  <el-dialog
    v-model="dialogVisible"
    title="结果录入"
    width="70%"
    :before-close="handleClose"
    class="result-record-dialog"
  >
    <div v-if="record" class="result-record">
      <!-- 患者信息 -->
      <el-card class="patient-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>患者信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ record.patientName }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>电话：</label>
              <span>{{ record.patientPhone }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>体检ID：</label>
              <span>{{ record.id }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>体检日期：</label>
              <span>{{ formatDate(record.checkupDate) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 体检项目录入 -->
      <el-card class="items-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>体检项目结果录入</span>
            <div class="header-actions">
              <el-button type="primary" size="small" @click="handleBatchSave">
                <el-icon><Check /></el-icon>
                批量保存
              </el-button>
              <el-button size="small" @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </template>
        
        <el-form ref="formRef" :model="formData" label-width="100px">
          <div class="items-grid">
            <div
              v-for="(item, index) in checkupItems"
              :key="item.id"
              class="item-card"
              :class="{ 'completed': item.status === 'completed' }"
            >
              <div class="item-header">
                <h4>{{ item.name }}</h4>
                <el-tag :type="getItemStatusType(item.status)" size="small">
                  {{ getItemStatusText(item.status) }}
                </el-tag>
              </div>
              
              <div class="item-content">
                <el-form-item :label="'检查结果'" :prop="`items.${index}.result`">
                  <el-input
                    v-model="formData.items[index].result"
                    placeholder="请输入检查结果"
                    :disabled="item.status === 'completed'"
                  />
                </el-form-item>
                
                <el-form-item :label="'数值'" :prop="`items.${index}.value`">
                  <el-input
                    v-model="formData.items[index].value"
                    placeholder="请输入数值"
                    :disabled="item.status === 'completed'"
                  >
                    <template #append>{{ item.unit }}</template>
                  </el-input>
                </el-form-item>
                
                <el-form-item :label="'正常范围'">
                  <el-input
                    :value="item.normalRange"
                    readonly
                    placeholder="正常范围"
                  />
                </el-form-item>
                
                <el-form-item :label="'异常标识'" :prop="`items.${index}.abnormal`">
                  <el-select
                    v-model="formData.items[index].abnormal"
                    placeholder="请选择"
                    :disabled="item.status === 'completed'"
                    style="width: 100%"
                  >
                    <el-option label="正常" value="normal" />
                    <el-option label="偏高" value="high" />
                    <el-option label="偏低" value="low" />
                    <el-option label="异常" value="abnormal" />
                  </el-select>
                </el-form-item>
                
                <el-form-item :label="'备注'" :prop="`items.${index}.remark`">
                  <el-input
                    v-model="formData.items[index].remark"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注信息"
                    :disabled="item.status === 'completed'"
                  />
                </el-form-item>
                
                <el-form-item :label="'检查医生'" :prop="`items.${index}.doctor`">
                  <el-select
                    v-model="formData.items[index].doctor"
                    placeholder="请选择医生"
                    :disabled="item.status === 'completed'"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="doctor in doctors"
                      :key="doctor.id"
                      :label="doctor.name"
                      :value="doctor.name"
                    />
                  </el-select>
                </el-form-item>
                
                <div class="item-actions">
                  <el-button
                    v-if="item.status !== 'completed'"
                    type="success"
                    size="small"
                    @click="handleSaveItem(index)"
                  >
                    <el-icon><Check /></el-icon>
                    保存
                  </el-button>
                  
                  <el-button
                    v-if="item.status === 'completed'"
                    type="warning"
                    size="small"
                    @click="handleEditItem(index)"
                  >
                    <el-icon><Edit /></el-icon>
                    修改
                  </el-button>
                  
                  <el-button
                    size="small"
                    @click="handleResetItem(index)"
                  >
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon>
          确认提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  items: []
})

// 模拟体检项目数据
const checkupItems = ref([
  {
    id: 1,
    name: '血常规',
    category: '血液检查',
    status: 'in_progress',
    normalRange: '4.0-10.0',
    unit: '×10^9/L'
  },
  {
    id: 2,
    name: '尿常规',
    category: '尿液检查',
    status: 'in_progress',
    normalRange: '阴性',
    unit: ''
  },
  {
    id: 3,
    name: '肝功能',
    category: '生化检查',
    status: 'in_progress',
    normalRange: '9-50',
    unit: 'U/L'
  },
  {
    id: 4,
    name: '肾功能',
    category: '生化检查',
    status: 'in_progress',
    normalRange: '44-133',
    unit: 'μmol/L'
  },
  {
    id: 5,
    name: '心电图',
    category: '心脏检查',
    status: 'in_progress',
    normalRange: '正常心律',
    unit: ''
  },
  {
    id: 6,
    name: 'B超检查',
    category: '影像检查',
    status: 'pending',
    normalRange: '无异常',
    unit: ''
  }
])

const doctors = ref([
  { id: 1, name: '张医生' },
  { id: 2, name: '李医生' },
  { id: 3, name: '王医生' },
  { id: 4, name: '陈医生' },
  { id: 5, name: '刘医生' }
])

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible && props.record) {
    initFormData()
  }
})

// 方法
const initFormData = () => {
  formData.items = checkupItems.value.map(item => ({
    id: item.id,
    result: '',
    value: '',
    abnormal: 'normal',
    remark: '',
    doctor: ''
  }))
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSaveItem = (index) => {
  const item = formData.items[index]
  const checkupItem = checkupItems.value[index]
  
  if (!item.result) {
    ElMessage.warning('请输入检查结果')
    return
  }
  
  if (!item.doctor) {
    ElMessage.warning('请选择检查医生')
    return
  }
  
  // 保存项目结果
  checkupItem.status = 'completed'
  checkupItem.result = item.result
  checkupItem.value = item.value
  checkupItem.abnormal = item.abnormal
  checkupItem.remark = item.remark
  checkupItem.doctor = item.doctor
  checkupItem.completedAt = new Date().toLocaleString('zh-CN')
  
  ElMessage.success(`${checkupItem.name} 结果已保存`)
}

const handleEditItem = (index) => {
  const checkupItem = checkupItems.value[index]
  checkupItem.status = 'in_progress'
  ElMessage.info(`${checkupItem.name} 已切换为编辑模式`)
}

const handleResetItem = (index) => {
  const item = formData.items[index]
  Object.assign(item, {
    result: '',
    value: '',
    abnormal: 'normal',
    remark: '',
    doctor: ''
  })
  
  const checkupItem = checkupItems.value[index]
  checkupItem.status = 'in_progress'
  
  ElMessage.success('项目已重置')
}

const handleBatchSave = () => {
  let savedCount = 0
  
  formData.items.forEach((item, index) => {
    const checkupItem = checkupItems.value[index]
    
    if (checkupItem.status === 'in_progress' && item.result && item.doctor) {
      checkupItem.status = 'completed'
      checkupItem.result = item.result
      checkupItem.value = item.value
      checkupItem.abnormal = item.abnormal
      checkupItem.remark = item.remark
      checkupItem.doctor = item.doctor
      checkupItem.completedAt = new Date().toLocaleString('zh-CN')
      savedCount++
    }
  })
  
  if (savedCount > 0) {
    ElMessage.success(`已保存 ${savedCount} 个项目结果`)
  } else {
    ElMessage.warning('没有可保存的项目')
  }
}

const handleReset = () => {
  ElMessageBox.confirm(
    '确定要重置所有项目吗？此操作将清空所有未保存的数据。',
    '重置确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    initFormData()
    checkupItems.value.forEach(item => {
      if (item.status === 'completed') {
        item.status = 'in_progress'
      }
    })
    ElMessage.success('已重置所有项目')
  }).catch(() => {
    // 用户取消
  })
}

const handleSubmit = async () => {
  try {
    // 检查是否有未完成的项目
    const pendingItems = checkupItems.value.filter(item => item.status !== 'completed')
    
    if (pendingItems.length > 0) {
      const result = await ElMessageBox.confirm(
        `还有 ${pendingItems.length} 个项目未完成，确定要提交吗？`,
        '提交确认',
        {
          confirmButtonText: '确定提交',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    }
    
    // 模拟提交API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('结果录入完成')
    emit('success')
    handleClose()
  } catch {
    // 用户取消
  }
}

const getItemStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    in_progress: 'warning',
    completed: 'success'
  }
  return statusMap[status] || 'info'
}

const getItemStatusText = (status) => {
  const statusMap = {
    pending: '待检查',
    in_progress: '检查中',
    completed: '已完成'
  }
  return statusMap[status] || '未知'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.result-record-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.result-record {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.patient-info-card,
.items-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 60px;
  margin-right: 8px;
}

.info-item span {
  color: #2c3e50;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.item-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.item-card.completed {
  background: #f0f9ff;
  border-color: #67c23a;
}

.item-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.item-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.item-content :deep(.el-form-item) {
  margin-bottom: 0;
}

.item-content :deep(.el-form-item__label) {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.item-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .items-grid {
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  }
}

@media (max-width: 768px) {
  .result-record-dialog {
    width: 95% !important;
  }
  
  .result-record-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .items-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .item-card {
    padding: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item label {
    min-width: auto;
    margin-right: 0;
  }
  
  .item-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .item-actions {
    flex-direction: column;
  }
  
  .item-actions .el-button {
    width: 100%;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .header-actions {
    flex-direction: column;
  }
  
  .header-actions .el-button {
    width: 100%;
  }
}
</style>